import { createRouter, createWebHistory } from 'vue-router'

import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import useLoginStore from '@/stores/user/index.js'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/home'
    },
    {
      path: '/home',
      component: () => import('@/views/home/home.vue')
    },
    {
      path: '/publish',
      component: () => import('@/views/article/publish-article.vue')
    },
    {
      path: '/detail',
      component: () => import('@/views/article/detail-article.vue')
    },
    {
      path: '/article-list',
      component: () => import('@/views/person/person-list.vue')
    },
    {
      path: '/user',
      component: () => import('@/views/person/user.vue')
    },
    {
      path: '/person-article',
      component: () => import('@/views/person/cpns/person-article.vue')
    },
    {
      path: '/:pathMatch(.*)',
      component: () => import('@/not-found/not-found.vue')
    }
  ]
})

//进度条的加载小圆球不要
NProgress.configure({ showSpinner: false })
//定义不需要登录的路由
const whiteList = ['/home', '/detail']
router.beforeEach((to, from, next) => {
  NProgress.start()
  const loginStore = useLoginStore()
  if (whiteList.includes(to.path)) {
    //放行
    next()
  } else {
    //需要登录，判断是否登录
    if (loginStore.token) {
      //方向
      next()
    } else {
      //弹出弹窗登录窗口
      loginStore.isShow = true
      //重定向到首页
      router.next({ path: '/home', query: { redirect: to.fullPath } })
    }
  }
})

router.afterEach((to, from, next) => {
  NProgress.done()
})

export default router
